//
// RegexFileStrainer
//
// Copyright (C) jextra.net.
//
//  This file is part of the Crack build system.
//
//  The Crack build system is free software; you can redistribute it 
//  and/or modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  The Crack build system is distributed in the hope that it will be 
//  useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with the Crack build system; if not, write to the Free
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
//  02111-1307 USA.
//

package net.jextra.crack.type;

import java.io.*;
import java.util.*;
import java.util.regex.*;
import net.jextra.crack.*;

/**
 * <p>
 * A {@link FileStrainer} that allows you to specify a number of include and exclude regular expressions that are used
 * to compare with JUST the file name (not the directory path).
 * </p><p>
 * Note, the regular expression ONLY matches the file name and not the path. Use a {@link DirStrainer} directory
 * strainer in the constructor or specify it with {@link #setDirStrainer(DirStrainer)} if you wish to filter
 * directories.
 * </p><p>
 * An example is to include only java files ( ".*\\.java" ).
 * </p><p>
 * Logic:
 * <ol>
 *      <li>If no "includes" specified, goto #4.
 *      <li>For each include, see if there is a match. If so, goto #4.
 *      <li>File should not be included. STOP
 *      <li>For each exclude, see if there is a maatch. If so, do not include.
 *      <li>File should be included. STOP
 * </ol>
 * </p>
 */
public class RegexFileStrainer implements FileStrainer
{
    // ============================================================
    // Fields
    // ============================================================

    private DirStrainer dirStrainer;
    private ArrayList<String> includeNameRegexs;
    private ArrayList<String> excludeNameRegexs;
    private CombinatorialFileStrainerFilenameFilter filter;

    // ============================================================
    // Constructors
    // ============================================================

    /**
     * Initializes the strainer to return all files in all sub-directories.
     */
    public RegexFileStrainer()
    {
        init();
    }

    /**
     * Initializes the strainer to return all files in the directories strained by the given dirStrainer.
     */
    public RegexFileStrainer( DirStrainer dirStrainer )
    {
        init();
        this.dirStrainer = dirStrainer;
    }

    // ============================================================
    // Methods
    // ============================================================

    // ----------
    // public
    // ----------

    public RegexFileStrainer include( String regex )
    {
        includeNameRegexs.add( regex );
        return this;
    }

    public RegexFileStrainer exclude( String regex )
    {
        excludeNameRegexs.add( regex );
        return this;
    }

    public DirStrainer getDirStrainer()
    {
        return dirStrainer;
    }

    public void setDirStrainer( DirStrainer dirStrainer )
    {
        this.dirStrainer = dirStrainer;
    }

    @Override
    public Collection<File> getFiles( File rootDir )
    {
        assert rootDir != null : "rootDir can not be null";
        assert rootDir.isDirectory() : String.format( "rootDir [%s] must be a directory", rootDir.getAbsolutePath() );

        Collection<File> files = new LinkedHashSet<File>();

        for ( File dir : dirStrainer.getDirs( rootDir ) )
        {
            for ( File file : dir.listFiles( filter ) )
            {
                files.add( file );
            }
        }

        return files;
    }

    // ----------
    // private
    // ----------

    private void init()
    {
        includeNameRegexs = new ArrayList<String>();
        excludeNameRegexs = new ArrayList<String>();
        dirStrainer = new RegexDirStrainer();
        filter = new CombinatorialFileStrainerFilenameFilter();
    }

    private boolean matchFile( File file )
        throws IOException
    {
        //
        // Do includes first.
        //
        boolean matches = includeNameRegexs.isEmpty();
        for ( String regex : includeNameRegexs )
        {
            if ( matchesName( file, regex ) )
            {
                matches = true;
                break;
            }
        }

        // Did not match any includes, reject.
        if ( !matches )
        {
            return false;
        }

        //
        // Do excludes last.
        //
        for ( String regex : excludeNameRegexs )
        {
            if ( matchesName( file, regex ) )
            {
                return false;
            }
        }

        return true;
    }

    private boolean matchesName( File file, String regex )
        throws IOException
    {
        Pattern p = Pattern.compile( regex );
        Matcher m = p.matcher( file.getName() );
        return m.matches();
    }

    // ============================================================
    // Inner Classes
    // ============================================================

    private class CombinatorialFileStrainerFilenameFilter implements FilenameFilter
    {
        @Override
        public boolean accept( File dir, String name )
        {
            try
            {
                File file = new File( dir, name );
                if ( file.isDirectory() )
                {
                    return false;
                }
                else
                {
                    return matchFile( file );
                }
            }
            catch ( IOException ex )
            {
                throw new CrackException( ex );
            }
        }
    }
}
